package com.helmlabs.grouper.search.service;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.helmlabs.grouper.search.model.Indexable;


public class IndexerServiceImpl implements IndexerService {

	public void index(Object obj) {
		if (obj instanceof Indexable) {
			try {
				Directory directory = FSDirectory.getDirectory("c:/helmlabs/index");
				IndexWriter iwriter = new IndexWriter(directory, new StandardAnalyzer());
				iwriter.setMaxFieldLength(25000);
				iwriter.addDocument(((Indexable)obj).toDocument());
				iwriter.optimize();
				iwriter.close();
				directory.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	public void remove(Object obj) {
		if (obj instanceof Indexable) {
			try {
				Document doc = ((Indexable)obj).toDocument();
				Directory directory = FSDirectory.getDirectory("c:/helmlabs/index");
				IndexSearcher searcher = new IndexSearcher(directory);
				QueryParser parser = new QueryParser("id",new StandardAnalyzer());
				Query q = parser.parse(doc.get("id"));
				Hits hits = searcher.search(q);
				ArrayList<Integer> toDelete = new ArrayList<Integer>();
				for (int i=0; i<hits.length(); i++){
					toDelete.add(hits.id(i));
				}
				searcher.close();
				IndexReader reader = IndexReader.open(directory);				
				for (int j=0; j<toDelete.size(); j++){
					reader.deleteDocument(toDelete.get(j));
				}
				reader.close();
				directory.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	

}
